<template>
  <div
    id="code-editor"
    ref="codeEditorRef"
    style="min-height: 600px; height: 80vh"
  />
  <!--  <a-button @click="fillValue">填充值</a-button>-->
</template>

<script setup lang="ts">
import * as monaco from "monaco-editor";
import {
  computed,
  defineProps,
  onMounted,
  ref,
  toRaw,
  watch,
  withDefaults,
} from "vue";

/**
 * 定义组件属性类型
 */
interface Props {
  value: string;
  language: string;
  handleChange: (v: string) => void;
  fontSize: number;
}

const props = withDefaults(defineProps<Props>(), {
  value: () => "",
  language: () => "java",
  handleChange: (v: string) => {
    console.log(v);
  },
  fontSize: () => 18,
});

const codeEditorRef = ref();
const codeEditor = ref();

// const fillValue = () => {
//   if (!codeEditor.value) {
//     return;
//   }
//   toRaw(codeEditor.value).setValue("新的值");
// };

watch(
  () => props.language,
  (newLang) => {
    const editor = toRaw(codeEditor.value);
    const model = editor.getModel();
    if (newLang == "java") {
      editor.setValue(`// 请不要修改类名，类名必须为Main
public class Main {
    public static void main(String[] args) {

    }
}`);
    } else {
      editor.setValue("");
    }

    if (model) {
      monaco.editor.setModelLanguage(model, newLang); // 使用 `setModelLanguage` 更新语言
    }
  }
);

watch(
  () => props.fontSize,
  (newSize) => {
    const editor = toRaw(codeEditor.value);
    editor.updateOptions({ fontSize: newSize });
  }
);

onMounted(() => {
  if (!codeEditorRef.value) {
    return;
  }
  codeEditor.value = monaco.editor.create(codeEditorRef.value, {
    value: props.value,
    language: props.language,
    fontSize: props.fontSize,
    automaticLayout: true,
    minimap: {
      enabled: true,
    },
    readOnly: false,
    theme: "vs-dark",
    // lineNumbers: "off",
    // roundedSelection: false,
    // scrollBeyondLastLine: false,
  });

  // 编辑 监听内容变化
  codeEditor.value.onDidChangeModelContent(() => {
    props.handleChange(toRaw(codeEditor.value).getValue());
  });
});
</script>

<style scoped></style>
